﻿namespace Jhong.FunMVCBlog.Admin.Controllers
{
    using Jhong.FunMVC;
    using Jhong.FunMVCBlog.Core.Data;
    using Jhong.FunMVCBlog.Core.Entity;
    using Jhong.FunMVCBlog.Core.Enum;
    using Jhong.FunMVCBlog.Core.Infrastructure;
    using Model;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Text;

    public class PostController : SecurityController
    {
        public ActionResult List()
        {
            return View();
        }

        private ArticlesData _articleData = new ArticlesData();

        public ActionResult EditPost(string id)
        {
            var tags = new TagData().GetAllTagName();
            ViewData["tags"] = string.Join(",", tags);

            var categoryies = new CategoryData().GetAllCategorySelectList();
            var model = new BlogArticleViewModel();

            if (false == string.IsNullOrWhiteSpace(id))
            {
                var entity = this._articleData.GetByID(Guid.Parse(id));
                if (null == entity) goto g1;
                model.ID = entity.ID;
                model.CategoryID = entity.CategoryID;
                model.Content = entity.Content;
                model.IsPublish = entity.IsPublist == PublishStatus.Publish;
                model.IsTop = entity.IsTop == TopStatus.Top;
                model.PublishTime = entity.PublishTime;
                model.Summary = entity.Summary;
                model.Title = entity.Title;
                model.CreateTime = entity.CreateTime;

                model.TagName = this._articleData.GetAllTags(Guid.Parse(id));

                foreach (var c in categoryies)
                {
                    if (c.Value != entity.CategoryID.ToString()) continue;
                    c.Selected = true;
                }
            }

        g1: ViewData["model"] = model;
            ViewData["categoryies"] = categoryies;
            return View();
        }

        [HttpPost]
        public ActionResult EditPost(BlogArticleViewModel model)
        {
            var m2 = new Articles();
            m2.Content = model.Content;
            m2.CategoryID = model.CategoryID;
            m2.IsDelete = DeleteStatus.No;
            m2.IsPublist = model.IsPublish ? PublishStatus.Publish : PublishStatus.Draft;
            m2.IsTop = model.IsTop ? TopStatus.Top : TopStatus.Normal;
            m2.LastModifyTime = DateTime.Now;
            m2.PublishTime = (model.IsPublish && model.PublishTime == DateTime.MinValue) || (model.IsPublish && model.UpdatePublishTime) ? DateTime.Now : model.PublishTime;
            m2.Summary = model.Summary;
            m2.Title = model.Title;

            bool res = false;
            if (model.ID == Guid.Empty)
            {
                m2.ID = Guid.NewGuid();
                m2.CreateTime = DateTime.Now;
                res = this._articleData.InsertArticle(m2, model.TagName);
            }
            else
            {
                m2.CreateTime = model.CreateTime;
                m2.ID = model.ID;
                res = this._articleData.UpdateArticle(m2, model.TagName);
            }
            return AjaxResult(res, res ? "保存成功" : "保存失败");
        }

        public ActionResult ImageUpload()
        {
            var file = Request.Forms.Files[0];
            var year = DateTime.Now.Year.ToString();
            var month = DateTime.Now.Month.ToString();
            var day = DateTime.Now.Day.ToString();
            var imgSavePath = Path.Combine("Static", "Img", year, month, day);
            if (false == Directory.Exists(imgSavePath)) Directory.CreateDirectory(imgSavePath);
            var fileName = string.Format("{0}{1}", Guid.NewGuid().ToString("N"), Path.GetExtension(file.FileName));
            var savePath = Path.Combine(imgSavePath, fileName).Replace("\\", "/");
            file.SaveAs(Path.Combine(WebSiteRootPath, savePath));
            var dic = new Dictionary<string, string>();
            dic.Add("state", "SUCCESS");
            dic.Add("url", savePath.StartsWith("/") ? savePath : "/" + savePath);
            dic.Add("originalName", Path.GetFileName(file.FileName));
            dic.Add("name", fileName);
            dic.Add("size", file.ContentLength.ToString());
            dic.Add("type", Path.GetExtension(fileName));
            var sb = new StringBuilder();
            sb.Append("{");
            foreach (var d in dic)
            {
                sb.Append(string.Format("\"{0}\":\"{1}\",", d.Key, d.Value));
            }
            if (sb[sb.Length - 1] == ',') sb.Remove(sb.Length - 1, 1);
            sb.Append("}");
            return Content(sb.ToString());
        }

        public ActionResult GetData(int pageIndex, int itemsPerPage)
        {
            var data = this._articleData.GetList(pageIndex, itemsPerPage);
            var page = data.GetPageHelper();
            return AjaxResult(true, data: new { Items = data.Items, Page = page.GetPageHtml() });
        }

        public ActionResult DeleteArticle(Guid id)
        {
            var res = this._articleData.DeleteArticle(new Articles() { ID = id });
            return AjaxResult(res, res ? "删除成功" : "删除失败");
        }
    }
}